<?php

defined('SYSPATH') or die('Access error!');

/**
 * 全站的基类
 * ============================================================================
 * 功能描述： 
 *      用户的初始化以及常用的一些方法
 * ============================================================================
 * $Author: liuxudong $
 */
abstract class Controller_Main extends Controller
{

    protected $user_detail = array();
    protected $setting = array();
    protected $settings = array();
    protected $same_user_profile;

    public function before()
    {
        parent::before();
        $this->user_detail = Session::instance()->get('user');
        if (empty($this->user_detail))
        {
            $user_cookie = Cookie::get('JSW_USER');
            if (!empty($user_cookie['username']) && !empty($user_cookie['password']))
            {
                $user = Model::factory('user');
                if ($user->check_user($user_cookie['username'], $user_cookie['password']))
                {
                    $user->login($user_cookie);
                }
            }
        }
        $this->setting = Model::factory('setting');
        $this->settings = $this->setting->get_all_setting();
        $this->template->assign('web_name', $this->settings['web_name']);
        //获取首页的导航
        $menu_list = $this->get_cache_file('menu');
        if (isset($menu_list['home']) && !empty($menu_list['home']))
        {
            $this->template->assign('home_menu', $menu_list['home']);
        }
    }

    public function after()
    {
        $this->template->assign('media_path', $this->template->media_path);
        $this->template->assign('css_path', URL::site($this->template->media_path) . '/' . 'css');
        $this->template->assign('images_path', URL::site($this->template->media_path) . '/' . 'images');
        $this->template->assign('js_path', URL::site('static/js'));
        $this->template->assign('site_url', URL::site());
        $this->template->assign('token', CSRF::set_csrf_token());
        $this->template->assign('captcha', Captcha::instance()->render());
        $this->template->assign('user', $this->user_detail);
        $this->template->assign('messages', Message::get());
        $this->template->assign('position', Breadcrumbs::render());
        if ($this->template->name != '' && $this->template->cache_name != '')
        {
            $this->template->display($this->template->name, $this->template->cache_name);
        } elseif ($this->template->name != '')
        {
            $this->template->display($this->template->name);
        }

        if (Core::$environment === 'production')
        {
            echo View::factory('profiler/stats');
        }
        parent::after();
    }

    /**
     *  判断是否登录
     * @return type
     */
    public function logged_in()
    {
        return count($this->user_detail) > 0;
    }

    public function set_define_position($word = '', $url = '')
    {
        Breadcrumbs::add($word, $url);
    }

    /**
     * 设置用户的权限
     */
    public function set_user_privilege()
    {
        Model_User::factory('user')->set_user_privilege();
    }

    //设置SEO资料
    public function set_seo($seo_arr)
    {
        $title = '';
        $keywords = '';
        $description = '';
        if (Arr::validate_arr($seo_arr))
        {
            if (isset($seo_arr['title']))
            {
                $title = $seo_arr['title'];
            }

            if (isset($seo_arr['keywords']))
            {
                $keywords = $seo_arr['keywords'];
            }

            if (isset($seo_arr['description']))
            {
                $description = $seo_arr['description'];
            }
        }
        $this->template->assign('meta', $meta = Meta::factory($title, $keywords, $description)->render());
    }

    /**
     *  生成模板的问题缓存id
     * @param type $cache_id
     * @return type
     */
    public function create_template_cache_id($cache_id)
    {
        return sprintf('%X', crc32($cache_id));
    }

    /**
     * 验证post提交的数据
     * 
     * @return  bool
     */
    public function valid_post($post = FALSE)
    {
        if (isset($post['token']))
        {
            if (!CSRF::check_csrf_token($post['token']))
            {
                Message::error(__('token error'));
                return FALSE;
            }
        }

        if (isset($post['captcha']))
        {
            if (!Captcha::valid($post['captcha']))
            {
                Message::error(__('captcha error'));
                return FALSE;
            }
        }

        return TRUE;
    }

    //判断是否允许（权限相关）
    public function is_allowed($url = '', $data = '')
    {
        if (!Model::factory('user')->is_allowed($this->request, $data))
        {
            Message::error(__('access error'));
            $this->request->redirect($url);
            exit;
        }

        return TRUE;
    }

    //保存积分
    public function save_points($to_user_id, $code, $detail_id = '', $from_user_id = 0)
    {
        return Model_User_Points::factory('user_points')->save_points($to_user_id, $code, $detail_id, $from_user_id = 0);
    }

    //保存经验
    public function save_experience($to_user_id, $code, $detail_id = '', $from_user_id = 0)
    {
        return Model_User_Experience::factory('user_experience')->save_experience($to_user_id, $code, $detail_id, $from_user_id = 0);
    }

    //发送站内信
    public function send_message($message_arr)
    {
        Model::factory('user_message')->send_message($message_arr);
    }

    //处理表单提交的数据
    public function handle_post($data)
    {
        $data_temp = array();
        if (Arr::validate_arr($data))
        {
            foreach ($data as $key => $value)
            {
                $data_temp[$key] = isset($value) ? trim($value) : '';
            }
        }
        unset($data);
        return $this->unset_post($data_temp);
    }

    public function unset_post($post, $fileds = array('submit', 'action', 'captcha', 'token'))
    {
        if (Arr::validate_arr($fileds))
        {
            foreach ($post as $key => $value)
            {
                if (in_array($key, $fileds))
                {
                    unset($post[$key]);
                }
            }
        }
        return $post;
    }

    public function handle_parent_id($data)
    {
        $data = array_reverse($data);
        if (count($data) == 1 || (count($data) > 1 && $data[0] != 0))
        {
            return $data[0];
        } elseif (count($data) > 1 && $data[0] == 0)
        {
            return $data[1];
        } else
        {
            return FALSE;
        }
    }

    //单张图片处理-返回图片的名称
    public function save_simple_file($dir, $filed)
    {
        //处理上传
        if (isset($_FILES))
        {
            $uploads = Upload::instance($dir)->upload($filed, 'png|jpg|gif');
            if (count($uploads) > 0)
            {
                return $uploads[0]['file_realname'];
            }
        }

        return '';
    }

    //返回图片的详细信息
    public function save_simple_detail($dir, $filed)
    {
        //处理上传
        if (isset($_FILES))
        {
            $uploads = Upload::instance($dir)->upload($filed, 'png|jpg|gif');
            if (count($uploads) > 0)
            {
                return $uploads;
            }
        }

        return '';
    }

    public function redirect_url()
    {
        $redirect_url = '';
        if (!empty($this->request->uri))
        {
            $redirect_url = '?redirect_url=' . URL::site($this->request->uri);
        }
        
        return $redirect_url;
    }

    //设置缓存文件
    public function set_cache_file($category_type, $data)
    {
        $category_data = Core::config('data_cache');
        return Cache::instance()->write($category_data['file'][$category_type], $data);
    }

    //获取普通数据的缓存
    public function get_cache_file($category_type)
    {
        $category_data = Core::config('data_cache');
        if (file_exists($category_data['file'][$category_type]))
        {
            return Cache::instance()->read($category_data['file'][$category_type]);
        }
    }

    //返回等级多维数组
    public function get_date_as_array($current_id, $category_type)
    {
        $data = $this->get_cache_file($category_type);
        Newtree::instance()->setTree($data, 'id', 'parent_id', 'name');
        $temp = Newtree::instance()->getArrayList($current_id);
        Newtree::instance()->delete();
        return $temp;
    }

    //获取分类的option
    public function get_category_cache_option($category_type, $selected_id = 0, $current_id = 0)
    {
        $category_data = Core::config('data_cache');
        $data = $this->get_cache_file($category_type);
        Newtree::instance()->setTree($data, 'id', 'parent_id', 'name');
        if ($current_id == 0)
        {
            $current_id = $category_data['id'][$category_type];
        }
        $temp = Newtree::instance()->get_tree($current_id, $selected_id);
        Newtree::instance()->delete();
        return $temp;
    }

    //获取城市的缓存文件
    public function get_area_cache_file()
    {
        $area_category = $this->get_cache_file('area');
        $area = array();
        if (Arr::validate_arr($area_category))
        {
            foreach ($area_category as $key => $value)
            {
                if ($value['id'] == SYSTEM_AREA_CATEGORY)
                {
                    continue;
                }
                if ($value['parent_id'] == SYSTEM_AREA_CATEGORY)
                {
                    $area['province'][$key] = $value;
                } else
                {
                    $area['city'][$key] = $value;
                }
            }
        }
        return $area;
    }

    //跳转到404
    public function show_404()
    {
        $this->request->redirect('error/show');
    }

    // 获取当前位置(分类的)
    public function get_category_position($id, $type, $url, $index = TRUE)
    {
        $category_list = $this->get_cache_file($type);
        Newtree::instance()->setTree($category_list, 'id', 'parent_id', 'name');
        $position_arr = Newtree::instance()->get_pos($id);
        Newtree::instance()->delete();
        if (Arr::validate_arr($position_arr))
        {
            foreach ($position_arr as $value)
            {
                if ($value['parent_id'] == 0)
                {
                    if ($index == TRUE)
                    {
                        Breadcrumbs::add($value['name'], URL::site($url));
                    }
                    continue;
                }
                Breadcrumbs::add($value['name'], URL::site($url . '/' . $value['id']));
            }
        }
    }

    //title需要的字符串（分类的名称）
    public function get_category_title($id, $type)
    {
        $category_list = $this->get_cache_file($type);
        Newtree::instance()->setTree($category_list, 'id', 'parent_id', 'name');
        $position_arr_temp = Newtree::instance()->get_pos($id);
        Newtree::instance()->delete();
        $position_arr = array_reverse($position_arr_temp);
        if (Arr::validate_arr($position_arr))
        {
            $str = '';
            foreach ($position_arr as $value)
            {
                $str .= $value['name'] . ' - ';
            }

            return rtrim(trim($str), '-');
        }
    }

    //获取分类页面的seo资料
    public function get_category_seo($id, $type)
    {
        $category_list = $this->get_cache_file($type);
        $title = $this->get_category_title($id, $type);
        if (Arr::validate_arr($category_list))
        {
            $seo_arr = array(
                'title' => $title,
                'keywords' => $category_list[$id]['keywords'],
                'description' => $category_list[$id]['description'],
            );
            $this->set_seo($seo_arr);
        }
    }

    //某个信息的详细的内容页面的seo资料
    public function detail_seo($category_id, $type, $title, $keyword, $description)
    {
        //获取问答的分类id
        $category_seo = $this->get_category_title($category_id, $type);
        $title = $title . ' - ' . $category_seo;

        $seo_arr = array(
            'title' => $title,
            'keywords' => $keyword,
            'description' => $description,
        );

        $this->set_seo($seo_arr);
    }

    //根据缓存文件获取某个分类的所有子分类
    public function get_category_childs($id, $type)
    {
        $category_list = $this->get_cache_file($type);
        Newtree::instance()->setTree($category_list, 'id', 'parent_id', 'name');
        $childs_arr = Newtree::instance()->getChilds($id);
        Newtree::instance()->delete();
        return $childs_arr;
    }

}